import { Types } from './Types';

/**
 * - 作者: DoooReyn
 * - 日期: 2023.10.29
 * - 名称: Objects
 * - 描述: 对象辅助方法
 */
export class Objects {
    /**
     * 深度冻结对象
     * @param obj 对象
     * @returns
     */
    static deepFreeze(obj: Record<string | number | symbol, any>) {
        Object.freeze(obj);

        const keys = Object.keys(obj);
        for (const key of keys) {
            const value = obj[key];
            if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
                this.deepFreeze(value);
            }
        }

        return obj;
    }

    /**
     * 有损拷贝
     * @param t 目标
     * @returns
     */
    static cloneInLossy<T>(t: T): T {
        return JSON.parse(JSON.stringify(t));
    }

    /**
     * 浅拷贝
     * @param t 目标
     * @returns
     */
    static cloneInShallow<T>(t: T): T {
        if (!t) return t;

        if (Types.isArray(t)) {
            return (t as any[]).map((v) => this.cloneInShallow(v)) as unknown as T;
        } else if (Types.isObject(t)) {
            return Object.assign(Object.create(Object.getPrototypeOf(t)), t);
        }

        return t;
    }

    /**
     * 深拷贝
     * @param t 目标
     * @returns
     */
    static cloneInDeep<T>(t: T): T {
        if (!t) return t;

        if (Types.isArray(t)) {
            return (t as any[]).map((v) => this.cloneInDeep(v)) as unknown as T;
        } else if (Types.isObject(t)) {
            const object = Object.create({});
            Object.entries(t).map(([k, v]: [string, any]) => {
                object[k] = this.cloneInDeep(v);
            });
            return object as T;
        }

        return t;
    }
}
